﻿@*@{
        ViewBag.Title = "财务结算单";
        Layout = "~/Views/Shared/_Form.cshtml";
    }
    @using Raffles.OA.Data;
    @using Raffles.OA.Utility;
    @{
        var data = new ViewDataDictionary();
        data.Add("FormType", ProjectFormEnum.FinanceSettlement.ToString());
        Html.RenderPartial("QuotationForm", data);
    }
    <script type="text/javascript">
        $(function () {
            $('.pay,.bank,.attention').parent().parent().hide();
            //分段的财务结算单表头不允许修改
            $('div[name="editForm"]').each(function () {
                $(this).find('input,select').attr('disabled', 'disabled');
            })
        })
    </script>*@
@{
    ViewBag.Title = "成本结算单";
    Layout = "~/Views/Shared/_Form.cshtml";
    var projectPrePayDay = CacheHelper.GetCache("ProjectPrePayDay") ?? 0;
    var projectRemainPayDay = CacheHelper.GetCache("ProjectRemainPayDay") ?? 0;
}
@using Raffles.OA.Data;
@using Raffles.OA.Utility;
<link href="/Content/plugin/bootstrap.datepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<link href="/Content/plugin/bootstrap.table/1.12.0/bootstrap-table.min.css" rel="stylesheet" />
<link href="/Content/plugin/zTree/v3/css/metroStyle/metroStyle.min.css" rel="stylesheet" />
<link href="/Content/sale/css/quotationForm.css" rel="stylesheet" />
<style media="print">
    body {
        height: auto !important;
    }

    @@page {
        margin: 0;
    }
</style>
<form id="form" class="form-horizontal m" role="form">
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table">
                <tr>
                    <td rowspan="2">
                        <img src="/Content/login/img/logo.png" />
                    </td>
                    <td>
                        <span class="text-bold">总部：</span>6 Raffles Quay, #14-02, Singapore 179094
                    </td>
                    <td rowspan="2" class="text-center">
                        <img src="/Content/qrcode.png" width="60" height="60" style="margin:5px" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="text-bold">官网：</span>www.sinbc.org
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <span><i class="fa fa-phone-square text-red"></i> 400 7999 189</span>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-12">
            <hr class="red-hr">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-12 text-center">
            <h3 class="text-bold text-black">
                团组成本结算单(货币：<span class="currencyCN" col="SettlementCurrencyCN">新币</span>)
            </h3>
        </div>
    </div>
    <div class="form-group" name="editForm">
        <label class="control-label col-sm-2 headLeftTitle">甲方名称：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headLeftValue">
            <select class="form-control required" id="customerId" col="CustomerId" name="CustomerId">
                <option value="">请选择渠道或输入对接人姓名</option>
            </select>
            <input type="hidden" id="customerName" col="CustomerName" />
        </div>
        <label class="control-label col-sm-2 headRightTitle">入境日期：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headRightValue">
            <div class='input-group date' id="dateGo">
                <input type='text' id="departureDate" col="DepartureDate" name="DepartureDate" class="form-control required" placeholder="入境日期" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group" name="editForm">
        <label class="control-label col-sm-2 headLeftTitle">乙方名称：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headLeftValue">
            <p>新加坡中国经济文化发展中心</p>
        </div>
        <label class="control-label col-sm-2 headRightTitle">离境日期：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headRightValue">
            <div class='input-group date' id="dateBack">
                <input type='text' id="returnDate" col="ReturnDate" name="ReturnDate" class="form-control required" placeholder="离境日期" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group" name="editForm">
        <label class="control-label col-sm-2 headLeftTitle">项目名称：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headLeftValue">
            <input type="text" col="Name" name="Name" class="form-control required" placeholder="请输入项目名称" />
        </div>
        <label class="control-label col-sm-2 headRightTitle">出行天数：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headRightValue">
            <input type="text" id="dayTotal" col="DayTotal" name="DayTotal" class="form-control required" placeholder="出行天数" disabled />
        </div>
    </div>
    <div class="form-group" name="editForm">
        <label class="control-label col-sm-2 headLeftTitle">合同编号：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headLeftValue">
            <input type="text" col="ContractCode" name="ContractCode" class="form-control required" placeholder="请输入合同编号" />
        </div>
        <label class="control-label col-sm-2 headRightTitle">报价日期：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 headRightValue">
            <div class='input-group date' id="dateQuotation">
                <input type='text' id="quotationDate" col="QuotationDate" name="QuotationDate" class="form-control required" placeholder="报价日期" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group" name="editForm">
        <label class="control-label col-sm-2 headLeftTitle">团队人数：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 flex-container headLeftValue">
            <div>
                <input type="number" id="adultTotal" col="AdultTotal" name="AdultTotal" class="form-control required" min="1" placeholder="请输入成人人数" />
            </div>
            <div>
                <input type="number" id="childTotal" col="ChildTotal" name="ChildTotal" class="form-control" placeholder="请输入儿童人数" />
            </div>
            <div>
                <input type="number" id="teamLeader" col="TeamLeader" name="TeamLeader" class="form-control" placeholder="请输入领队人数" />
            </div>
        </div>
        <label class="control-label col-sm-2 headRightTitle">方案顾问：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4 flex-container headRightValue">
            <div class="col-sm-3" style="padding:0">
                <input type="text" id="saleManagerName" col="SaleManagerName" name="SaleManagerName" class="form-control required" value="@OperatorProvider.Provider.GetCurrent().RealName" disabled />
            </div>
            <div class="col-sm-9 nopdf" style="padding:0">
                <select class="form-control" id="involveId" col="InvolveId" name="InvolveId" multiple>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group nopdf">
        <label class="control-label col-sm-2">收客汇率：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4">
            <input type="number" id="settlementRate" col="SettlementRate" name="SettlementRate" class="form-control required" min="0.01" placeholder="请输入结算汇率" />
        </div>
        <label class="control-label col-sm-2">到款汇率：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4">
            <input type="number" id="paymentRate" col="PaymentRate" name="PaymentRate" class="form-control required" min="0.01" placeholder="请输入付款汇率" />
        </div>
    </div>
    <div class="form-group nopdf">
        <label class="control-label col-sm-2">税率(%)：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4"> 
            <input type="number" id="taxRate" col="TaxRate" name="TaxRate" class="form-control required" min="0" placeholder="请输入地接税率" />
        </div>
        <label class="control-label col-sm-2">结算货币：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4">
            <select class="form-control required" id="settlementCurrency" col="SettlementCurrency" name="SettlementCurrency">
                <option value="">请选择结算货币</option>
            </select>
            <input type="hidden" id="settlementCurrencyCN" col="SettlementCurrencyCN" />
        </div>
    </div>
    <div class="form-group nopdf" name="editForm">
        <label class="control-label col-sm-2">报价类目：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4">
            <div id="quotationItemCode" col="QuotationItemCode"></div>
        </div>
        <label class="control-label col-sm-2">行程分段：<font class="red">*</font></label>
        <div class="col-xs-12 col-sm-4">
            <select class="form-control required" id="countrySegment" col="CountrySegment" name="CountrySegment" multiple>
            </select>
        </div>
    </div>
    <!--行程-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table trip" name="trip">
                <thead>
                    <tr>
                        <th width="150px">天数</th>
                        <th width="150px">日期</th>
                        <th>行程</th>
                        <th>航班</th>
                        <th>起降时间</th>
                        <th>接送</th>
                        <th width="120px">工时</th>
                        <th>早餐</th>
                        <th>午餐</th>
                        <th>晚餐</th>
                    </tr>
                </thead>
                <tbody id="trip_body">
                </tbody>
            </table>
        </div>
    </div>
    <!--住宿-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item hotel" name="hotel">
                <thead>
                    <tr>
                        <th width="35%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.Hotel.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 团队住宿</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量(晚)</th>
                        <th width="10%">房间</th>
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="hotel_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--餐饮-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item restaurant" name="restaurant">
                <thead>
                    <tr>
                        <th width="35%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.Restaurant.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 团队餐饮</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量(餐)</th>
                        <th width="10%">人数</th>
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="restaurant_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--交通-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item transportation" name="transportation">
                <thead>
                    <tr>
                        <th width="45%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.Transportation.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 交通导游</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量</th> 
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="transportation_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--景区-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item scenicArea" name="scenicArea">
                <thead>
                    <tr>
                        <th width="45%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.ScenicArea.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 景点门票</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">人数</th> 
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="scenicArea_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--公务-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item groupOfficial" name="groupOfficial">
                <thead>
                    <tr>
                        <th width="45%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.GroupOfficial.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 团组公务</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量</th>
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="groupOfficial_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--培训-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item groupActivity" name="groupActivity">
                <thead>
                    <tr>
                        <th width="45%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.GroupActivity.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 团组培训</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量</th>
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="groupActivity_body">
                </tbody>
            </table>
        </div>
    </div>

    <!--其他-->
    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table item addition" name="addition">
                <thead>
                    <tr>
                        <th width="35%">
                            <a id="btnAdd" class="item" onclick="PageUI.addQuotationItem('@QuotationItemEnum.Addition.ToString()')" href="javascript:void(0);"><i class="fa fa-plus-circle fa-lg text-red" name="add"></i> 其他费用</a>
                            -
                            <span class="font-money">0.00</span>
                        </th>
                        <th width="10%">数量</th>
                        <th width="10%">人数</th>
                        <th width="15%">成本单价</th>
                        <th width="15%">成本小计</th>
                        <th width="10%">利润小计</th>
                        <th width="10%">利润率</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="addition_body">
                </tbody>
            </table>
        </div>
    </div>

    <div class="form-group" style="margin-bottom: 0;">
        <div class="col-sm-12">
            <table class="table pay">
                <tr>
                    <td width="50%" class="text-bold"></td>
                    <td width="10%"></td>
                    <td width="25%" class="text-bold text-right">成本总计<span class="currencyCN" col="SettlementCurrencyCN">新币</span>(税前)：</td>
                    <td class="text-bold text-center">
                        <span class="font-green" id="totalSGDBeforeTax" col="TotalSGDBeforeTax">$0.00</span>
                    </td>
                </tr>
                <tr>
                    <td class="text-bold"></td>
                    <td class="text-bold"></td>
                    <td class="text-bold text-right">成本总计人民币(税前)：</td>
                    <td class="text-bold text-center">
                        <span class="font-green" id="totalRMBBeforeTax" col="TotalRMBBeforeTax">￥0.00</span>
                    </td>
                </tr>
                <tr>
                    <td class="text-bold"></td>
                    <td class="text-bold"><span id="personTotal"></span></td>
                    <td class="text-bold text-right">人均成本人民币(税前)：</td>
                    <td class="text-bold text-center">
                        <span class="font-green" id="averageRMBBeforeTax" col="AverageRMBBeforeTax">￥0.00</span>
                    </td>
                </tr> 
            </table>
        </div>
    </div> 
</form>
<script src="/Content/plugin/bootstrap.datepicker/js/bootstrap-datetimepicker.min.js"></script>
<script src="/Content/plugin/zTree/v3/js/ztree.min.js"></script>
<script>moment.locale('zh-cn');</script>
<script type="text/javascript">
    var PageUI = {
        FormFiled: {
            DepartureDate: $('#departureDate'),//出发时间
            ReturnDate: $('#returnDate'),//回程时间
            DayTotal: $('#dayTotal'),//出行天数
            AdultTotal: $('#adultTotal'),//成人人数
            ChildTotal: $('#childTotal'),//儿童人数
            SettlementRate: $('#settlementRate'),//结算汇率
            PaymentRate: $('#paymentRate'),//付款汇率
            TaxRate: $('#taxRate'),//结算税率
            CountrySegment: $('#countrySegment'),//行程分段
            PersonTotal: $('#personTotal'),//总人数
            TotalSGDBeforeTax: $('#totalSGDBeforeTax'),//税前新币合计
            TotalRMBBeforeTax: $('#totalRMBBeforeTax'),//税前人民币合计
            AverageRMBBeforeTax: $('#averageRMBBeforeTax'),//税前人均人民币合计(只计算成人)
        },
        FormValue: {
            TripItemList: [],
            QuotationItemList: [], 
        },
        initValue: {
            Id: frame.request("id"),
            Type: frame.request("type"),
            CountrySegment: [],
            ItemDetail: [],
            QuotationActivityDetail: [],//团组培训明细
            QuotationTransportDetail: [],//交通导游明细
            DayFood: [],//行程早午晚
            QuotationItemSelect: [],//报价选项
        },
        initDateControl: (id, defaultDate, callback) => {
            $("#" + id).datetimepicker({
                format: 'YYYY-MM-DD',
                showClear: true,
                locale: moment.locale('zh-cn'),
                widgetPositioning: {
                    horizontal: 'left',
                    vertical: 'bottom'
                },
                useCurrent: false,
                focusOnShow: false,
                defaultDate: defaultDate,
            }).on('dp.change', callback);
        },
        initSelectControl: (id, url, placeholder, isTags, defaultValue, callback) => {
            var _self = PageUI;
            frame.ajax({
                url,
                type: 'get',
                async: false,
                success: function (obj) {
                    if (obj.success) {
                        $("#" + id).frameSelect({
                            placeholder,
                            search: true,
                            data: obj.data,
                            default: defaultValue,
                            tags: isTags,
                            onChange: callback
                        });
                    }
                }
            });
        },
        firstLetterToLower: (str) => {
            if (!str) return str;
            if (str.length === 1) return str.toLowerCase();
            return str.charAt(0).toLowerCase() + str.slice(1);
        },
        renderEnumSelect: (id, data, placeholder, isTags, defaultValue, callback) => {
            $("#" + id).frameSelect({
                data,
                placeholder,
                default: defaultValue,
                tags: isTags,
                search: true,
                onChange: callback
            });
        },
        loadDictionarySelect: (code) => {
            var _self = PageUI;
            frame.ajax({
                url: '@Url.Action("GetDictionaryIdByCode", "Common", new { area = "" })' + '?code=' + code,
                type: 'get',
                async: false,
                success: function (obj) {
                    if (obj.success) {
                        _self.initValue.DayFood = obj.data;
                    }
                }
            });
        },
        renderComboBoxTree: (id, url) => {
            $("#" + id).frameComboBoxTree({
                url,
                async: false,
                expandLevel: -1
            });
        },
        padWithZero: (num, fill) => {
            let len = ('' + num).length;
            if (fill > len) {
                num = Array(fill - len + 1 || 0).join("0") + num;
            }
            return num;
        },
        formatDaysDate: (date) => {
            return moment(date).format('YYYY.MM.DD dddd');
        },
        //1、出行天数变化 重新渲染行程安排
        //2、出行天数变化 重新渲染团队住宿晚数和团队正餐数
        dayTotalInputEvent: (dateGo, days) => {
            var _self = PageUI;
            $('#trip_body').empty();
            if (!!days) {
                for (var i = 0; i < days; i++) {
                    PageUI.dynamicRenderDays(dateGo, i, days);
                }
                _self.day2Update(days);
            }
        },
        personTotalInputEvent: ($adultId, $childrenId) => {
            var _self = PageUI;
            var adultTotal = !!$adultId.val() ? parseInt($adultId.val()) : 0;
            var childrenTotal = !!$childrenId.val() ? parseInt($childrenId.val()) : 0;
            var result = [];
            if (!!adultTotal) {
                result.push(`<span class='text-bold text-info fontnumber'>${adultTotal}</span> 成人`)
            }
            _self.FormFiled.PersonTotal.empty().append(result.join(''));
            _self.calcMoney();
            _self.person2Update(adultTotal, childrenTotal);
        },
        triggerForPageInputEvent: (id) => {
            $('#' + id).trigger('input');
        },
        moneyInputEvent: (quantityId, numberId, priceId, totalId, isTotal) => {
            var _self = PageUI;
            var quantity = 1;
            if ($('#' + quantityId).length != 0) { quantity = $('#' + quantityId).val() }
            var number = $('#' + numberId).val();
            var price = $('#' + priceId).val();
            var total = $('#' + totalId).val();
            if (!isTotal) {
                //根据数量单价计算总价
                if (!!number && !!price) {
                    $('#' + totalId).val((quantity * number * price).toFixed(2));
                } else {
                    $('#' + totalId).val('');
                }
            }
            else {
                //根据总价计算单价
                if (!!number && !!price && !!total) {
                    $('#' + priceId).val((total / (quantity * number)).toFixed(2))
                }
            }
            _self.calcMoney();
        },
        anyInputEvent: (id) => {
            var _self = PageUI;
            $('#' + id).on("input", (e) => {
                _self.calcMoney();
            });
        },
        //计算各报价分项金额汇总
        calcItemCodeTotal: () => {
            $('table[name]').filter(function () {
                return $(this).hasClass('item');
            }).each(function () {
                var $table = $(this);
                var $total = $table.find('thead th:first-child').find('span[class="font-money"]');
                var totalMoney = 0;
                $table.find('tbody tr').each(function (i) {
                    if (!!$(this).find($('input[type="number"][name^="total_"]')).val()) {
                        totalMoney = totalMoney + parseFloat($(this).find($('input[type="number"][name^="total_"]')).val());
                    }
                });
                $total.text(totalMoney.toFixed(2));
            });
        },
        //付款方式里定金和比例的变化带来的换算
        calcMoney: () => {
            var _self = PageUI;
            //结算汇率
            var settlementRate = !!_self.FormFiled.SettlementRate.val() ? _self.FormFiled.SettlementRate.val() : 0;
            //成人数量
            var adultTotal = _self.FormFiled.AdultTotal.val();
            //税前结算货币对应的总金额
            var sumTotal = 0;
            $('input[type="number"][name^="total_"]').each(function () {
                if (!!$(this).val()) {
                    sumTotal = sumTotal + parseFloat($(this).val());
                }
            });
            //税前新币合计
            _self.FormFiled.TotalSGDBeforeTax.text(frame.formatCurrency(parseInt(sumTotal), "USD"));
            //税前人民币合计
            _self.FormFiled.TotalRMBBeforeTax.text(frame.formatCurrency(parseInt(sumTotal * settlementRate), "CNY"));
            //税前人均人民币合计(只计算成人)
            if (!!adultTotal && adultTotal > 0) {
                _self.FormFiled.AverageRMBBeforeTax.text(frame.formatCurrency(parseInt(sumTotal * settlementRate / adultTotal), "CNY"));
            }
            _self.calcSaleProfit();
            _self.calcItemCodeTotal();
        },
        recoverPay: () => {
            var _self = PageUI;
            _self.FormFiled.AdvancePayRate.val('0.00');
            _self.FormFiled.AdvancePaySGD.val('');
            _self.FormFiled.AdvancePayRMB.val('');
            _self.FormFiled.PrePaySGD.val('');
            _self.FormFiled.PrePayRMB.val('');
            _self.FormFiled.RemainPaySGD.val('');
            _self.FormFiled.RemainPayRMB.val('');
        },
        addDestination: ($this) => {
            var _self = PageUI;
            var html = [];
            var cityId = `city_${frame.getGuid()}`;
            html.push("<div class='del_container'>");
            html.push("<i class=\"fa fa-times delete-icon\" onclick=\"PageUI.delDestination($(this))\" name=\"delete\"></i>");
            html.push("<div id=\"" + cityId + "\" name=\"" + cityId + "\">");
            html.push("</div>");
            html.push("</div>");
            $this.before(`${html.join('')}`);
            //追加行程城市
            _self.renderComboBoxTree(cityId, '@Url.Action("GetDestinationTreeSelect", "BaseInfo")')
            _self.dynamicAddValidateRule(cityId + "_input");
        },
        delDestination: ($this) => {
            var _self = PageUI;
            $this.parent().remove();
        },
        delDynamicRow: ($this) => {
            var _self = PageUI;
            $this.parent().parent().remove();
            _self.calcMoney();
        },
        dynamicRefreshSelectData: (idPrefix, data) => {
            var _self = PageUI;
            if ($(`select[id^="${idPrefix}"]`).length > 0) {
                $(`select[id^="${idPrefix}"]`).find('option').remove();
                $(`select[id^="${idPrefix}"]`).each(function () {
                    _self.renderEnumSelect($(this).attr('id'), data, '请选择', false, null, null);
                });
            }
        },
        dynamicAddValidateRule: (id) => {
            $("#" + id).rules("add", {
                required: true,
                messages: {
                    required: "必填"
                }
            });
        },
        inputTooltipEvent: (id) => {
            $('#' + id).on('input', function (event) {
                $('#' + id).attr('data-original-title', $('#' + id).val()).tooltip('show');
            });
        },
        showItemDetail: (itemControlId, priceId, code, segmentId) => { 
            var _self = PageUI;
            var selectItemId = $('#' + itemControlId).val();
            if (!!selectItemId) {
                if (parseFloat(selectItemId) > 0) {
                    switch (code) {
                        //交通导游
                        case "@QuotationItemEditEnum.Transportation.ToString()":
                            frame.openDialog({
                                title: "交通导游成本明细",
                                content: '@Url.Content("/Sale/Project/QuotationTransportDetailForm")' + '?id=' + selectItemId + "&projectId=" + _self.initValue.Id + "&priceId=" + priceId + "&code=" + code + "&segmentId=" + $('#' + segmentId).val() + "&title=" + $('#' + itemControlId).find('option:selected').text() + "&startDate=" + _self.FormFiled.DepartureDate.val() + "&days=" + _self.FormFiled.DayTotal.val(),
                                width: ($(window).width() - 100) + 'px',
                                height: ($(window).height() - 100) + 'px',
                                btn: _self.initValue.Type == "view" ? null : ["保存", "关闭"],
                                callback: function (index, layero) {
                                    var iframeWin = window[layero.find('iframe')[0]['name']];
                                    iframeWin.saveForm(index);
                                }
                            });
                            break;
                        //团组培训
                        case "@QuotationItemEditEnum.GroupActivity.ToString()":
                            frame.openDialog({
                                title: "团组培训成本明细",
                                content: '@Url.Content("/Sale/Project/QuotationItemDetailForm")' + '?id=' + selectItemId + "&priceId=" + priceId + "&code=" + code + "&segmentId=" + + $('#' + segmentId).val(),
                                width: '750px',
                                height: ($(window).height() - 20) + 'px',
                                callback: function (index, layero) {
                                    var iframeWin = window[layero.find('iframe')[0]['name']];
                                    iframeWin.saveForm(index);
                                }
                            });
                            break;
                    }
                }
                else {
                    frame.msgWarning("手动输入内容无需编辑明细项！");
                } 
            }
            else {
                frame.msgWarning("请选择成本明细项！");
            }
        },
        relatePrice: (itemId, quantityId, numberId, priceId, totalId, code) => {
            var _self = PageUI;
            var quantity = 1;
            frame.ajax({
                url: '@Url.Content("/Sale/BaseInfo/GetBaseItemPrice")' + '?id=' + itemId + "&code=" + code,
                type: 'get',
                async: false,
                success: function (obj) {
                    if (obj.success) {
                        if (!!obj.data) {
                            $('#' + priceId).val(obj.data.toFixed(2)).trigger('input');
                        }
                        else {
                            $('#' + priceId).val('').trigger('input');
                        }
                    }
                }
            })
        },
        iCheckRender: () => {
            $('input[type=checkbox][name="guideChange"]').iCheck({
                checkboxClass: 'icheckbox-blue'
            });
        },
        iCheckGuideChange: (name) => {
            var _self = PageUI;
            var daysGuideChange
            $(`input[type=checkbox][name^='${name}']`).parent().attr("title", "更导");
            $(`input[type=checkbox][name^='${name}']`).on('ifChecked', function (event) {
                //汇总所有行程中选中复选框数
                if (!!_self.FormFiled.DayTotal.val()) {
                    daysGuideChange = $(`input[type=checkbox][id^='guideChangeDay_']:checked`).length;
                    //计算其他费用中的guideChangeNumber_
                    $(`.addition input[type=number][name^='quantity_']`).each(function (event) {
                        var inputId = $(this).attr('id');
                        $('#' + inputId).val(parseInt(_self.FormFiled.DayTotal.val()) + daysGuideChange).trigger('input');
                    });
                }
            });
            $(`input[type=checkbox][name^='${name}']`).on('ifUnchecked', function (event) {
                //汇总所有行程中选中复选框数
                if (!!_self.FormFiled.DayTotal.val()) {
                    daysGuideChange = $(`input[type=checkbox][id^='guideChangeDay_']:checked`).length;
                    //计算其他费用中的guideChangeNumber_
                    $(`.addition input[type=number][name^='quantity_']`).each(function (event) {
                        var inputId = $(this).attr('id');
                        $('#' + inputId).val(parseInt(_self.FormFiled.DayTotal.val()) + daysGuideChange).trigger('input');
                    });
                }
            });
        },
        //人数变化更新【团队餐饮、景点门票、其他费用】中的人数number_
        person2Update: (adult, child) => {
            $('.restaurant input[type=number][name^="number_"],.scenicArea input[type=number][name^="number_"],.addition input[type=number][name^="number_"]').each(function (event) {
                var inputId = $(this).attr('id');
                $('#' + inputId).val(adult + child).trigger('input');
            });
        },
        //出行天数变化-团队餐饮正餐数和住宿晚数quantity_
        day2Update: (days) => {
            var _self = PageUI;
            $('.hotel input[type=number][name^="quantity_"]').each(function (event) {
                var inputId = $(this).attr('id');
                $('#' + inputId).val(parseInt(days) - 1).trigger('input');
            });
            _self.food2Update();
        },
        //餐饮变化更新团队餐饮餐数
        food2Update: () => {
            var foodCount = $('#trip_body tr').find('select[name^="lunch_"],select[name^="dinner_"]').filter(function () {
                var selectedOption = $(this).find('option:selected');
                return selectedOption.text() === "✔";
            }).length;
            $('.restaurant input[type=number][name^="quantity_"]').each(function (event) {
                var inputId = $(this).attr('id');
                $('#' + inputId).val(foodCount).trigger('input');
            });
        },
        iCheckQuotationItemCodeChange: () => {
            var _self = PageUI;
            $('input[type=checkbox][name="quotationItemCode_checkbox"]').on('ifChecked', function (event) {
                var dom_class = `.${_self.firstLetterToLower(event.target.value)}`;
                $(dom_class).find('tbody').empty();
                $(dom_class).show();
            });
            $('input[type=checkbox][name="quotationItemCode_checkbox"]').on('ifUnchecked', function (event) {
                var dom_class = `.${_self.firstLetterToLower(event.target.value)}`;
                $(dom_class).find('tbody').empty();
                $(dom_class).hide();
                _self.calcMoney();//涉及行变化重新计算价格
            })
        },
        getQuotationItem: (code) => {
            var _self = PageUI;
            frame.ajax({
                url: "@Url.Action("GetProjectQuotationItem", "BaseInfo")" + "?code=" + code,
                type: 'get',
                async: false,
                success: function (obj) {
                    if (obj.success) {
                        _self.initValue.QuotationItemSelect.push({ Code: code, Item: obj.data });
                    }
                }
            });
        },
        addQuotationItem: (code) => {
            var _self = PageUI;
            //出行天数、团组人数、收客汇率、行程分段 没有维护是无法添加报价明细
            if (_self.FormFiled.DayTotal.val().length == 0 || _self.FormFiled.AdultTotal.val().length == 0 || _self.FormFiled.SettlementRate.val().length == 0 || _self.FormFiled.CountrySegment.val() == null) {
                frame.msgWarning("表头维护不完整！");
                return;
            }
            var html = [];
            var segmentId, itemId, quantityId, numberId, priceId, totalId;
            segmentId = `segment_${frame.getGuid()}`;
            itemId = `item_${frame.getGuid()}`;
            quantityId = `quantity_${frame.getGuid()}`;
            numberId = `number_${frame.getGuid()}`;
            priceId = `price_${frame.getGuid()}`;
            totalId = `total_${frame.getGuid()}`;
            html.push("<tr>");
            html.push("<td>");
            html.push("<div class=\"col-sm-12 flex-container\" style='padding-left:0'>");
            html.push("<div class=\"col-sm-3\" style='padding:0'>");
            html.push("<select id=\"" + segmentId + "\" name=\"" + segmentId + "\" class=\"form-control required\">");
            html.push("</select>");
            html.push("</div>");
            html.push("<div class=\"col-sm-9\" style='padding:0'>");
            html.push("<select id=\"" + itemId + "\" name=\"" + itemId + "\" class=\"form-control required\">");
            html.push("<option value=''>请选择</option>");
            html.push("</select>");
            html.push("</div>");
            if (code == "@QuotationItemEditEnum.Transportation.ToString()" || code == "@QuotationItemEditEnum.GroupActivity.ToString()") {
                html.push("<a class=\"item\" onclick=\"PageUI.showItemDetail('" + itemId + "','" + priceId + "','" + code + "','" + segmentId + "')\" href=\"javascript:void(0);\"><i class=\"fa fa-search-plus fa-lg text-blue\" name=\"view\"></i></a>");
            }
            html.push("</div>");
            html.push("</td>");
            //团队住宿晚数，团队餐数(午+晚)
            var totalnigntsORdayfoods = '';
            //人数(团队餐饮、景点门票、其他费用)
            var totalpersons = '';
            switch (code) {
                //团队住宿、团队餐饮、其他费用
                case "@QuotationItemEditEnum.Hotel.ToString()":
                case "@QuotationItemEditEnum.Restaurant.ToString()":
                case "@QuotationItemEditEnum.Addition.ToString()":
                    html.push("<td>");
                    if (code == "@QuotationItemEditEnum.Addition.ToString()") {
                        var daysGuideChange = 0;
                        var value = '';
                        //关联更导
                        if (!!_self.FormFiled.DayTotal.val()) {
                            daysGuideChange = $(`input[type=checkbox][id^='guideChangeDay_']:checked`).length;
                            value = daysGuideChange + parseInt(_self.FormFiled.DayTotal.val());
                        }
                        html.push("<div class=\"col-sm-12\">");
                        html.push("<input type=\"number\" id=\"" + quantityId + "\"name=\"" + quantityId + "\" class=\"form-control text-center required\" min=\"0\" placeholder=\"请输入\" value=\"" + value + "\" />");
                        html.push("</div>");
                    }
                    else {
                        if (code == "@QuotationItemEditEnum.Hotel.ToString()") {
                            totalnigntsORdayfoods = !!_self.FormFiled.DayTotal.val() ? _self.FormFiled.DayTotal.val() - 1 : '';
                        }
                        if (code == "@QuotationItemEditEnum.Restaurant.ToString()") {
                            totalnigntsORdayfoods = $('#trip_body tr').find('select[name^="lunch_"],select[name^="dinner_"]').filter(function () {
                                var selectedOption = $(this).find('option:selected');
                                return selectedOption.text() === "✔";
                            }).length;
                        }
                        html.push("<div class=\"col-sm-12\">");
                        html.push("<input type=\"number\" id=\"" + quantityId + "\" name=\"" + quantityId + "\" class=\"form-control text-center required\" min=\"0\" placeholder=\"数量\" value='" + totalnigntsORdayfoods + "'  />");
                        html.push("</div>");
                    }

                    html.push("</td>");
                    break;
                //交通导游、景点门票、团组公务、团组培训
                case "@QuotationItemEditEnum.Transportation.ToString()":
                case "@QuotationItemEditEnum.ScenicArea.ToString()":
                case "@QuotationItemEditEnum.GroupOfficial.ToString()":
                case "@QuotationItemEditEnum.GroupActivity.ToString()":

                    break;
            }
            if (code == "@QuotationItemEditEnum.Restaurant.ToString()" || code == "@QuotationItemEditEnum.ScenicArea.ToString()" || code == "@QuotationItemEditEnum.Addition.ToString()") {
                totalpersons = parseInt(_self.FormFiled.AdultTotal.val()) + parseInt(_self.FormFiled.ChildTotal.val())
            }
            else if (code == "@QuotationItemEditEnum.GroupOfficial.ToString()" || code == "@QuotationItemEditEnum.GroupActivity.ToString()") {
                totalpersons = 1;
            }
            html.push("<td>");
            html.push("<div class=\"col-sm-12 \">");
            html.push("<input type=\"number\" id=\"" + numberId + "\" name=\"" + numberId + "\" class=\"form-control text-center required\" min=\"0\" placeholder=\"数量\" value='" + totalpersons + "'  />");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12 flex-container\">");
            html.push("<input type=\"number\" id=\"" + priceId + "\" name=\"" + priceId + "\" class=\"form-control text-center required\" min=\"0\" placeholder=\"单价\"  />");
            html.push("<span class='font text-blue' name='salePrice'></span>");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12 flex-container\">");
            html.push("<input type=\"number\" id=\"" + totalId + "\" name=\"" + totalId + "\" class=\"form-control text-center required\" min=\"0\" placeholder=\"总价\"  />");
            html.push("<span class='font text-blue' name='saleTotal'></span>");
            html.push("</div>");
            html.push("</td>");

            html.push("<td class=\"text-center\">");
            html.push("<span class='font-green' name='profitTotal'>-</span>");
            html.push("</td>");

            html.push("<td class=\"text-center\">");
            html.push("<span class='font-green' name='profitRate'>-</span>");
            html.push("</td>");

            html.push("<td class=\"text-center\">");
            html.push("<a class=\"fa fa-minus-circle fa-lg text-red\" onclick=\"PageUI.delDynamicRow($(this))\"  href=\"javascript:void(0);\" title=\"删除行\" name=\"delete\"></a>");
            html.push("</td>");

            html.push("</tr>");
            $(`#${_self.firstLetterToLower(code)}_body`).append(html.join(''));
            //行程分段
            _self.renderEnumSelect(segmentId, frame.getJson(_self.initValue.CountrySegment), "请选择", false, null,null);
            //下拉项
            var filterQuotationItemSelect = _self.initValue.QuotationItemSelect.length == 0 ? [] : _self.initValue.QuotationItemSelect.filter(x => x.Code.toLowerCase() == code.toLowerCase());
            if (filterQuotationItemSelect.length == 0) {
                //没有缓存下拉值时填充下拉项全局变量
                _self.getQuotationItem(code);
                filterQuotationItemSelect = _self.initValue.QuotationItemSelect.filter(x => x.Code.toLowerCase() == code.toLowerCase())
            }
            _self.renderEnumSelect(itemId, frame.getJson(filterQuotationItemSelect[0].Item), "请选择", true, null,(e) => {
                _self.relatePrice(e.target.value, quantityId, numberId, priceId, totalId, code)
                $(e.target).valid();
            });
            //数量和金额绑定事件
            $(`#${quantityId},#${numberId},#${priceId}`).on('input', (e) => {
                _self.moneyInputEvent(quantityId, numberId, priceId, totalId, false);
            });
            //总价绑定事件
            $(`#${totalId}`).on('input', (e) => {
                _self.moneyInputEvent(quantityId, numberId, priceId, totalId, true);
            });
            $("input[type='number'][name^='quantity_'],input[type='number'][name^='number_'],input[type='number'][name^='price_'],input[type='number'][name^='total_']").addClass('font');
        },
        dynamicRenderDays: (dateGo, i, days) => {
            var _self = PageUI;
            var html = [];
            var segmentId, cityId, flightNoId, flightTimeId, serviceId, serviceHourId, breakfastId, lunchId, dinnerId;
            segmentId = `segment_${frame.getGuid()}`;
            cityId = `city_${frame.getGuid()}`;
            flightNoId = `flightNo_${frame.getGuid()}`;
            flightTimeId = `flightTime_${frame.getGuid()}`;
            serviceId = `service_${frame.getGuid()}`;
            serviceHourId = `serviceHour_${frame.getGuid()}`;
            breakfastId = `breakfast_${frame.getGuid()}`;
            lunchId = `lunch_${frame.getGuid()}`;
            dinnerId = `dinner_${frame.getGuid()}`;
            html.push("<tr>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12 flex-container\" style='padding-left:0'>");
            html.push("<div class=\"col-sm-12\" style='padding-left:0'>");
            html.push("<select id=\"" + segmentId + "\" name=\"" + segmentId + "\" class=\"form-control required\">");
            html.push("</select>");
            html.push("</div>");
            html.push(`<p style='min-width: 40px'>第${_self.padWithZero(i + 1, 2)}天</p>`);
            html.push("</div>");
            html.push("</td>");

            html.push(`<td><p>${_self.formatDaysDate(moment(dateGo).add(i, 'days'))}</p></td>`);

            html.push("<td>");
            html.push("<div class=\"col-sm-12 flex-container\" style=\"justify-content:center\" name=\"city\">");
            html.push("<div>");
            html.push("<div id=\"" + cityId + "\" name=\"" + cityId + "\">");
            html.push("</div>");
            html.push("</div>");
            html.push("<a class=\"item\" onclick=\"PageUI.addDestination($(this))\" href=\"javascript:void(0);\"><i class=\"fa fa-plus-circle fa-lg text-orange\" name=\"add\"></i></a>");
            html.push("<input id=\"guideChangeDay_" + cityId + "\" type=\"checkbox\" name=\"guideChange\">");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<input type=\"text\" id=\"" + flightNoId + "\" name=\"" + flightNoId + "\" class=\"form-control text-center\" placeholder=\"\" data-toggle=\"tooltip\" title=\"\" />");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<input type=\"text\" id=\"" + flightTimeId + "\" name=\"" + flightTimeId + "\" class=\"form-control text-center\" placeholder=\"\" data-toggle=\"tooltip\" title=\"\" />");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            //html.push("<input type=\"text\" id=\"" + serviceId + "\" name=\"" + serviceId + "\" class=\"form-control text-center\" placeholder=\"\" data-toggle=\"tooltip\" title=\"\" />");
            html.push("<select id=\"" + serviceId + "\" name=\"" + serviceId + "\" class=\"form-control\">");
            html.push("</select>");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<input type=\"number\" id=\"" + serviceHourId + "\" name=\"" + serviceHourId + "\" class=\"form-control text-center\" placeholder=\"\"  />");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<select id=\"" + breakfastId + "\" name=\"" + breakfastId + "\" class=\"form-control required\">");
            html.push("</select>");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<select id=\"" + lunchId + "\" name=\"" + lunchId + "\" class=\"form-control required\">");
            html.push("</select>");
            html.push("</div>");
            html.push("</td>");

            html.push("<td>");
            html.push("<div class=\"col-sm-12\">");
            html.push("<select id=\"" + dinnerId + "\" name=\"" + dinnerId + "\" class=\"form-control required\">");
            html.push("</select>");
            html.push("</div>");
            html.push("</td>");

            html.push("</tr>");

            $("#trip_body").append(html.join(''));
            //行程分段
            _self.renderEnumSelect(segmentId, frame.getJson(_self.initValue.CountrySegment), "请选择", false, null, null);
            //行程城市
            _self.renderComboBoxTree(cityId, '@Url.Action("GetDestinationTreeSelect", "BaseInfo")')
            //行程城市添加必填项校验
            _self.dynamicAddValidateRule(cityId + "_input");
            //行程安排--是否更导
            _self.iCheckRender();
            //接送
            _self.renderEnumSelect(serviceId, frame.getJson(@Html.Raw(typeof(ServiceEnum).EnumToCodeDictionaryString())), "请选择", false, (i == 0 ? "@ServiceEnum.ReceiveHour.ToString()" : (i == days - 1 ? "@ServiceEnum.DeliverHour.ToString()" : "")), null);
            //早餐、中餐、晚餐
            _self.renderEnumSelect(breakfastId, frame.getJson(_self.initValue.DayFood), null, false, null, null);
            //默认第一行早餐✖
            if (i == 0) { $('#' + breakfastId).frameSelect("setValue", $('#' + breakfastId).find("option").filter(function () { return $(this).text() === "✖" }).val()); }
            _self.renderEnumSelect(lunchId, frame.getJson(_self.initValue.DayFood), null, false, null, (e) => {
                _self.food2Update()
            });
            _self.renderEnumSelect(dinnerId, frame.getJson(_self.initValue.DayFood), null, false, null, (e) => {
                _self.food2Update()
            });
            //input-tootip
            _self.inputTooltipEvent(flightNoId);
            _self.inputTooltipEvent(flightTimeId);
            _self.inputTooltipEvent(serviceId);
            //计算更导在其他费用中变化的人数
            _self.iCheckGuideChange('guideChange');
        },
        init: () => {
            var _self = PageUI;
            //甲方名称
            _self.initSelectControl('customerId', "@Url.Action("GetChannelSelect", "Channel")", "请选择甲方名称", false, null, (e) => {
                $('#customerName').val($(e.target).find(":selected").text())
                $(e.target).valid();
            });
            //入境日期
            _self.initDateControl('dateGo', null, (e) => {
                if (!!e.date) {
                    var dtOldGo = !!e.date._i ? moment(e.date._i) : '1900-01-01';
                    var dtGo = moment(e.date);
                    var dtBack = _self.FormFiled.ReturnDate.val();
                    if (!!dtBack && !dtOldGo.isSame(dtGo, 'day')) {
                        if (dtGo.isAfter(moment(dtBack), 'day')) {
                            frame.msgError("入境日期不能大于离境日期");
                            $('#dateGo').datetimepicker('clear');
                            _self.FormFiled.DayTotal.val('');
                            return;
                        }
                        else {
                            _self.FormFiled.DayTotal.val(moment(dtBack).diff(dtGo, 'days') + 1)
                        }
                        _self.FormFiled.DayTotal.trigger('input');
                    }
                    $('#datePrePay').datetimepicker('clear');
                    $('#datePrePay').datetimepicker('defaultDate', dtGo.add(-@projectPrePayDay, 'days'));
                }
                else {
                    _self.FormFiled.DayTotal.val('').trigger('input');
                    $('#datePrePay').datetimepicker('clear');
                    $('#dateGo').datetimepicker('clear');
                }
            });
            //离境日期
            _self.initDateControl('dateBack', null, (e) => {
                if (!!e.date) {
                    var dtOldBack = !!e.date._i ? moment(e.date._i) : '1900-01-01';
                    var dtBack = moment(e.date);
                    var dtGo = _self.FormFiled.DepartureDate.val();
                    if (!!dtGo && !dtBack.isSame(dtOldBack, 'day')) {
                        if (dtBack.isBefore(moment(dtGo), 'day')) {
                            frame.msgError("离境日期不能小于入境日期");
                            $('#dateBack').datetimepicker('clear');
                            _self.FormFiled.DayTotal.val('');
                            return;
                        }
                        else {
                            _self.FormFiled.DayTotal.val(dtBack.diff(moment(dtGo), 'days') + 1)
                        }
                        _self.FormFiled.DayTotal.trigger('input');
                    }
                    $('#dateRemainPay').datetimepicker('clear');
                    $('#dateRemainPay').datetimepicker('defaultDate', dtBack.add(@projectRemainPayDay, 'days'));
                }
                else {
                    _self.FormFiled.DayTotal.val('').trigger('input');
                    $('#dateRemainPay').datetimepicker('clear');
                    $('#dateBack').datetimepicker('clear');
                }
            });
            //出行天数
            _self.FormFiled.DayTotal.on("input", (e) => {
                _self.dayTotalInputEvent(_self.FormFiled.DepartureDate.val(), e.target.value);
            });
            //报价日期
            _self.initDateControl('dateQuotation', new Date(), null);
            //团队人数
            _self.FormFiled.AdultTotal.on("input", (e) => {
                _self.personTotalInputEvent(_self.FormFiled.AdultTotal, _self.FormFiled.ChildTotal);
            });
            _self.FormFiled.ChildTotal.on("input", (e) => {
                _self.personTotalInputEvent(_self.FormFiled.AdultTotal, _self.FormFiled.ChildTotal);
            });
            //行程国家
            _self.initSelectControl('countrySegment', "@Url.Action("GetProjectSegmentSelect", "BaseInfo")", "请选择行程国家段", false, null, (e) => {
                _self.initValue.CountrySegment = [];
                $(e.target).find('option:selected').each(function () {
                    _self.initValue.CountrySegment.push({ Key: $(this).val(), Value: $(this).text() })
                });
                _self.dynamicRefreshSelectData('segment_', _self.initValue.CountrySegment);//联动刷新行程分段数据源
                $(e.target).valid();
            });
            //参与人员
            _self.initSelectControl('involveId', "@Url.Action("GetInvolveSelect", "Project")", "请选择参与人员", false, null, null);
            //加载早中晚餐数据
            _self.loadDictionarySelect('TripFood');
            //结算汇率
            _self.FormFiled.SettlementRate.on("input", (e) => {
                _self.calcMoney();
            });
            //付款汇率
            _self.FormFiled.PaymentRate.on("input", (e) => {
                _self.calcMoney();
            });
            //地接税率
            _self.FormFiled.TaxRate.on("input", (e) => {
                _self.calcMoney();
            });
            //结算货币(成本结算单-默认人民币)
            _self.initSelectControl('settlementCurrency', "@Url.Action("GetDictionaryCodeByCode", "Common", new { area = "" })" + '?code=SettlementCurrency', "请选择结算货币", false, "RMB", (e) => {
                $('span[class="currency"]').text(e.target.value);
                $('span[class="currencyCN"]').text($(e.target).find(":selected").text());
                $('#settlementCurrencyCN').val($(e.target).find(":selected").text());
                $(e.target).valid();
            });
            //报价类目
            var quotationItemCodeData = frame.getJson(@Html.Raw(typeof(QuotationItemEditEnum).EnumToCodeDictionaryString()))
            defaultData = quotationItemCodeData.map(item => item.Key);
            $("#quotationItemCode").frameCheckBox({
                data: quotationItemCodeData,
                default: defaultData,
                onCheck: function (event) {
                    var dom_class = `.${_self.firstLetterToLower(event.target.value)}`;
                    $(dom_class).find('tbody').empty();
                    $(dom_class).show();
                },
                onUncheck: function (event) {
                    var dom_class = `.${_self.firstLetterToLower(event.target.value)}`;
                    $(dom_class).find('tbody').empty();
                    $(dom_class).hide();
                    _self.calcMoney();//涉及行变化重新计算价格
                }
            });
            //编辑表单
            _self.editForm(_self.initValue.Id);
            //禁用一些成本结算单无法编辑的表单控件
            $('div[name="editForm"]').each(function () {
                $(this).find('input,select').attr('disabled', 'disabled');
            })
        },
        saveForm: (index) => {
            var _self = PageUI;
            var item = [];
            var itemTrip = [];
            var itemPay = [];
            if ($('#form').validate().form()) {
                $('table[name]').each(function (i) {
                    var $table = $(this);
                    var code = $table.attr('name');
                    switch (code) {
                        //团队住宿、团队餐饮、其他费用、交通导游、景点门票、团组公务、团组培训
                        case _self.firstLetterToLower("@QuotationItemEditEnum.Hotel.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.Restaurant.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.Addition.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.Transportation.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.ScenicArea.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.GroupOfficial.ToString()"):
                        case _self.firstLetterToLower("@QuotationItemEditEnum.GroupActivity.ToString()"):
                            $table.find('tbody tr').each(function () {
                                var $tr = $(this);
                                item.push(
                                    {
                                        SegmentId: $('#' + $tr.find('select[name^="segment_"]').attr('id')).val(),
                                        QuotationItemCode: code,
                                        ItemId: $('#' + $tr.find('select[name^="item_"]').attr('id')).val(),
                                        ItemName: $('#' + $tr.find('select[name^="item_"]').attr('id')).find(":selected").text(),
                                        Quantity: $('#' + $tr.find('input[name^="quantity_"]').attr('id')).val(),
                                        Number: $('#' + $tr.find('input[name^="number_"]').attr('id')).val(),
                                        ActivityDetail: _self.initValue.QuotationActivityDetail.filter(x => x.Code.toLowerCase() == code.toLowerCase() && x.SegmentId == $('#' + $tr.find('select[name^="segment_"]').attr('id')).val() && x.ItemId == $('#' + $tr.find('select[name^="item_"]').attr('id')).val()),
                                        TransportDetail: _self.initValue.QuotationTransportDetail.filter(x => x.Code.toLowerCase() == code.toLowerCase() && x.SegmentId == $('#' + $tr.find('select[name^="segment_"]').attr('id')).val() && x.ItemId == $('#' + $tr.find('select[name^="item_"]').attr('id')).val()),
                                        Price: $('#' + $tr.find('input[name^="price_"]').attr('id')).val(),
                                        SalePrice: $tr.find('span[name^="salePrice"]').text(),
                                        Total: $('#' + $tr.find('input[name^="total_"]').attr('id')).val(),
                                        SaleTotal: $tr.find('span[name^="saleTotal"]').text(),
                                    })
                            });
                            break;
                        default:
                            $table.find('tbody tr').each(function (i) {
                                var $tr = $(this);
                                var tripPlaceIds = [];
                                var tripPlaceNames = [];
                                //处理多个行程城市
                                $tr.find('input[name^="city_"]').each(function () {
                                    tripPlaceIds.push($(this).closest('div[name^="city_"]').attr('data-key'))
                                    tripPlaceNames.push($(this).closest('div[name^="city_"]').attr('data-value'))
                                });
                                itemTrip.push(
                                    {
                                        SegmentId: $('#' + $tr.find('select[name^="segment_"]').attr('id')).val(),
                                        Day: i + 1,
                                        TripDate: moment(_self.FormFiled.DepartureDate.val()).add(i, 'days').format('YYYY-MM-DD'),
                                        TripPlaceId: tripPlaceIds,
                                        TripPlaceName: tripPlaceNames,
                                        IsGuideChange: $('#' + $tr.find('input[type=checkbox][name="guideChange"]').attr('id')).is(':checked'),
                                        FlightNo: $('#' + $tr.find('input[name^="flightNo_"]').attr('id')).val(),
                                        FlightTime: $('#' + $tr.find('input[name^="flightTime_"]').attr('id')).val(),
                                        Service: $('#' + $tr.find('select[name^="service_"]').attr('id')).val(),
                                        //ServiceHour: $('#' + $tr.find('input[name^="serviceHour_"]').attr('id')).val(),
                                        BreakfastId: $('#' + $tr.find('select[name^="breakfast_"]').attr('id')).val(),
                                        BreakfastName: $('#' + $tr.find('select[name^="breakfast_"]').attr('id')).find(":selected").text(),
                                        LunchId: $('#' + $tr.find('select[name^="lunch_"]').attr('id')).val(),
                                        LunchName: $('#' + $tr.find('select[name^="lunch_"]').attr('id')).find(":selected").text(),
                                        DinnerId: $('#' + $tr.find('select[name^="dinner_"]').attr('id')).val(),
                                        DinnerName: $('#' + $tr.find('select[name^="dinner_"]').attr('id')).find(":selected").text()
                                    });
                            })
                    }
                    _self.FormValue.TripItemList = itemTrip;
                    _self.FormValue.QuotationItemList = item;
                });
                //保存之前调用一次价格计算
                _self.calcMoney();
                var postData = $('#form').getWebControls(
                    {
                        Id: _self.initValue.Id,
                        TripItemList: _self.FormValue.TripItemList,
                        QuotationItemList: _self.FormValue.QuotationItemList,
                        FormType: "@ProjectFormEnum.FinanceSettlement.ToString()"
                    });
                console.log(postData)
                //return;
                frame.ajax({
                    url: '@Url.Action("SaveQuotationForm","Project")',
                    type: 'post',
                    data: postData,
                    success: function (obj) {
                        if (obj.success) {
                            frame.msgSuccess(obj.message);
                            parent.searchGrid();
                            parent.layer.close(index);
                        }
                        else {
                            frame.msgError(obj.message);
                        }
                    }
                });
            }
            else {
                frame.msgWarning("表单维护不完整！");
            }
        },
        disableAllControl: () => {
            var _self = PageUI;
            if (_self.initValue.Type == "view") {
                //禁用所有的控件
                $(document).find('input,select').attr('disabled', 'disabled');
                $(document).find('i[name="add"],i[name="delete"],a[name="delete"]').hide()
            }
        },
        editRenderDayData: (data) => {
            $('table[name="trip"] tbody tr').each(function (i) {
                var $tr = $(this);
                //行程分段
                $('#' + $tr.find('select[name^="segment_"]').attr('id')).frameSelect('setValue', data[i].SegmentId);
                //是否更导
                if (data[i].IsGuideChange) {
                    $('#' + $tr.find('input[type=checkbox][name="guideChange"]').attr('id')).iCheck('check');
                }
                else {
                    $('#' + $tr.find('input[type=checkbox][name="guideChange"]').attr('id')).iCheck('uncheck');
                }
                //处理多个行程城市
                var cityCount = data[i].TripPlaceId.length;
                for (var len = 0; len < cityCount - 1; len++) {
                    $tr.find('a[class="item"]').trigger('click');
                }
                $tr.find('div[name^="city_"]').each(function (j, n) {
                    $(this).frameComboBoxTree('setValue', data[i].TripPlaceId[j]);
                });
                //航班
                $('#' + $tr.find('input[name^="flightNo_"]').attr('id')).val(data[i].FlightNo);
                //起降时间
                $('#' + $tr.find('input[name^="flightTime_"]').attr('id')).val(data[i].FlightTime);
                //接送
                $('#' + $tr.find('select[name^="service_"]').attr('id')).frameSelect('setValue', data[i].Service ?? "");
                //工时
                //$('#' + $tr.find('input[name^="serviceHour_"]').attr('id')).val(data[i].ServiceHour);
                //早餐
                $('#' + $tr.find('select[name^="breakfast_"]').attr('id')).frameSelect('setValue', data[i].BreakfastId);
                //午餐
                $('#' + $tr.find('select[name^="lunch_"]').attr('id')).frameSelect('setValue', data[i].LunchId);
                //晚餐
                $('#' + $tr.find('select[name^="dinner_"]').attr('id')).frameSelect('setValue', data[i].DinnerId);
            });
        },
        editQuotationItemData: (data) => {
            var _self = PageUI;
            $('table[name]').filter(function () {
                return $(this).hasClass('item');
            }).each(function () {
                var $table = $(this);
                var code = $table.attr('name');
                var itemList = data.filter(x => x.QuotationItemCode.toLowerCase() == code.toLowerCase());
                for (var x = 0; x < itemList.length; x++) {
                    $table.find('thead tr a[id="btnAdd"]').trigger('click');
                }
                $table.find('tbody tr').each(function (i) {
                    var $tr = $(this);
                    //行程分段
                    $('#' + $tr.find('select[name^="segment_"]').attr('id')).frameSelect('setValue', itemList[i].SegmentId);
                    //明细
                    if (itemList[i].ItemId === null || itemList[i].ItemId === undefined) {
                        itemList[i].ItemId = itemList[i].ItemName;
                        $('#' + $tr.find('select[name^="item_"]').attr('id')).append("<option value='" + itemList[i].ItemId + "'>" + itemList[i].ItemName +"</option>")
                    }
                    $('#' + $tr.find('select[name^="item_"]').attr('id')).frameSelect('setValue', itemList[i].ItemId);
                    //Quantity
                    $('#' + $tr.find('input[name^="quantity_"]').attr('id')).val(itemList[i].Quantity);
                    //Number
                    $('#' + $tr.find('input[name^="number_"]').attr('id')).val(itemList[i].Number);
                    //Price
                    $('#' + $tr.find('input[name^="price_"]').attr('id')).val(itemList[i].Price.toFixed(2));
                    //SalePrice
                    $tr.find('span[name="salePrice"]').text(itemList[i].SalePrice);
                    //Total
                    $('#' + $tr.find('input[name^="total_"]').attr('id')).val(itemList[i].Total.toFixed(2));
                    //SaleTotal
                    $tr.find('span[name="saleTotal"]').text(itemList[i].SaleTotal);
                });
            });
        },
        //计算销售小计和利润率
        calcSaleProfit: () => {
            $('table[name]').filter(function () {
                return $(this).hasClass('item');
            }).each(function () {
                $(this).find('tbody tr').each(function (index) {
                    var $tr = $(this);
                    var qty = $tr.find('input[name^="quantity_"]').length != 0 ? $tr.find('input[name^="quantity_"]').val() : 1;
                    var number = $tr.find('input[name^="number_"]').val();
                    var price = $tr.find('input[name^="price_"]').val();
                    var total = $tr.find('input[name^="total_"]').val();
                    var saleTotal = parseFloat($tr.find('span[name="saleTotal"]').text());
                    if (!!saleTotal) {
                        if (!!qty && !!number && !!price && !!total) {
                            var profitTotal = saleTotal - total;
                            //利润小计(销售合计-成本合计)
                            $tr.find('span[name="profitTotal"]').text(profitTotal.toFixed(2));
                            //利润率(销售利润率=利润/销售额)
                            $tr.find('span[name="profitRate"]').text((profitTotal * 100 / saleTotal).toFixed(2) + "%");
                            //利润小于0，红色背景高亮显示
                            if (profitTotal < 0) {
                                $tr.find('span[name="profitRate"]').parent().css("background", "#FF0000");
                                $tr.find('span[name="profitRate"]').css("color", "white");
                            }
                            else {
                                $tr.find('span[name="profitRate"]').parent().css("background", "none");
                                $tr.find('span[name="profitRate"]').css("color", "green");
                            }
                        }
                        else {
                            $tr.find('span[name="profitTotal"]').text('-');
                            $tr.find('span[name="profitRate"]').text('-');
                        }
                    }
                });
            })
        },
        editForm: (id) => {
            var _self = PageUI;
            if (id > 0) {
                frame.ajax({
                    url: '@Url.Action("SetQuotationForm","Project")' + '?projectId=' + id,
                    type: 'get',
                    success: function (obj) {
                        if (obj.success) {
                            console.log(obj.data)
                            //入境日期
                            obj.data.DepartureDate = moment(obj.data.DepartureDate).format('YYYY-MM-DD');
                            //离境日期
                            obj.data.ReturnDate = moment(obj.data.ReturnDate).format('YYYY-MM-DD');
                            //报价日期
                            obj.data.QuotationDate = moment(obj.data.QuotationDate).format('YYYY-MM-DD');
                            //团费新币
                            obj.data.TotalSGDBeforeTax = frame.formatCurrency(parseFloat(obj.data.TotalSGDBeforeTax), 'USD');
                            //团费人民币
                            obj.data.TotalRMBBeforeTax = frame.formatCurrency(parseFloat(obj.data.TotalRMBBeforeTax), 'CNY');
                            //团费人均
                            obj.data.AverageRMBBeforeTax = frame.formatCurrency(parseFloat(obj.data.AverageRMBBeforeTax), 'CNY');
                            $('#form').setWebControls(obj.data);
                            _self.iCheckQuotationItemCodeChange();
                            //报价类目
                            $('input[type="checkbox"][name="quotationItemCode_checkbox"]').iCheck('uncheck');//取消全部选中
                            $("#quotationItemCode").frameCheckBox('setValue', obj.data.QuotationItemCode);
                            $.each(obj.data.QuotationItemCode, function (i, val) {
                                //触发勾选的类目选中事件
                                $('input[type="checkbox"][name="quotationItemCode_checkbox"][value=' + val + ']').iCheck('check');
                            })

                            _self.FormFiled.AdultTotal.trigger('input');//目的是为了触发人均费用前面的显示

                            //行程天数
                            _self.FormValue.TripItemList = obj.data.TripItemList;
                            //报价明细
                            _self.FormValue.QuotationItemList = obj.data.QuotationItemList;
                            //触发出行天数input事件
                            _self.FormFiled.DayTotal.trigger('input');
                            _self.editRenderDayData(obj.data.TripItemList);
                            _self.editQuotationItemData(obj.data.QuotationItemList);
                            var detailTemp = [];
                            //赋值全局变量-交通导游下拉项明细 
                            $.each(obj.data.QuotationItemList, function (i, n) {
                                detailTemp = _self.initValue.QuotationTransportDetail;
                                _self.initValue.QuotationTransportDetail = detailTemp.concat(n.TransportDetail);
                            });
                            //赋值全局变量-团组培训下拉项明细
                            detailTemp = [];
                            $.each(obj.data.QuotationItemList, function (i, n) {
                                detailTemp = _self.initValue.QuotationActivityDetail;
                                _self.initValue.QuotationActivityDetail = detailTemp.concat(n.ActivityDetail);
                            });
                            //全部赋值完成之后重新调用一下价格计算
                            _self.calcMoney();
                            _self.disableAllControl();
                        }
                        else {
                            frame.msgError(obj.message);
                        }
                    }
                });
            };
        },
    }
    PageUI.init();
</script>